package com.oddpointcc.szpt.accounting.web;

import com.oddpointcc.szpt.accounting.pojo.Book;
import com.oddpointcc.szpt.accounting.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import com.oddpointcc.szpt.accounting.security.CustomUserDetails;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class LoginController {

	@Autowired
	private BookService bookService;

	@GetMapping(value = { "/login", "/" })
	public String login() {
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (principal instanceof CustomUserDetails == false) {
			return "login";
		}
		String role = ((CustomUserDetails) principal).getRole();
		if (role.equals("ROLE_ADMIN")) {
			return "redirect:/admin/";
		} else {
			throw new RuntimeException();
		}
	}

	@ResponseBody
	@GetMapping("/findBooks")
	public List<Book> findBooks(){
		return bookService.findBooks();
	}

}
